package rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("110.41.84.205");
        factory.setPort(5672);
        factory.setUsername("study");
        factory.setPassword("study");
        factory.setVirtualHost("Demo"); // 虚拟主机
        // 建立连接
        Connection connection = factory.newConnection();
        // 建立通信
        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare("hello",true,false,false,null);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(new String(body));
            }
        };
        // 消费消息
        channel.basicConsume("hello",true,consumer);
        Thread.sleep(2000);
        // 释放资源
        channel.close();
        connection.close();
    }
}
